import Taro from '@tarojs/taro'
import { type BaseEventOrig } from '@tarojs/components'

import { useUserStore } from './useUserStore'
import { useLoadingify } from './useLoadingify'
import { bindInfo, postPhone } from '@/apis/user'

const service = async (code: string) => {
  await postPhone(code)
  const res = await bindInfo()
  return res
}

export function useBindPhone() {
  const { getUserInfo } = useUserStore()
  const [loading, bindPhone] = useLoadingify(service, { showToast: true })

  const handle = async ({ detail: { code, errMsg } }: BaseEventOrig<{ code?: string; errMsg?: string }>) => {
    console.log(errMsg, code)

    if (!code) {
      // toast.error(errMsg)
      if (!errMsg?.includes('user deny')) {
        Taro.showModal({
          title: '提示',
          content: errMsg,
          confirmText: '知道了',
        })
      }

      return Promise.reject(errMsg)
    }

    const res = await bindPhone(code)

    console.log('[bindPhone]', res)

    const user = await getUserInfo()

    console.log('[user]', user)

    return user
  }

  return [loading, handle] as const
}
